package campeonatofutebol.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import campeonatofutebol.bean.Mural;
import campeonatofutebol.util.AdapterHolder;
import campeonatofutebol.util.CompartilharMensagemTask;
import campeonatofutebol.util.Servico;
import campeonatofutebol.util.WebServiceInterface;

import com.example.campeonatofutebol.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

public class GamePage extends Activity{

	private TextView t;
	private ListView l;
	private String tituloJogo;
	private String muralId;
	private String userId;
	private String userName;
	private Mural historicoChat;
	private ArrayAdapter<String> adapter;
	private EditText e;
	private Button bt;
	private GraphUser usuario ;
	private CheckBox chBox;
	Intent i;

	private static class MHandler extends Handler {
		GamePage gp;
		public  MHandler(GamePage gp) {
			this.gp = gp;
		}
		@Override
		public void handleMessage(Message msg) {  
			gp.post(msg.getData().getString("message"));
		}

	}

	/*	private Handler handler=new Handler() {
		@Override
		public void handleMessage(Message msg) {  
			post(msg.getData().getString("message"));
		}
	};*/
	private Handler handler = new MHandler(this);

	private  UiLifecycleHelper uiHelper;

	private  Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}


	};

	private  void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		Log.w("sessionState", "state : " + state.toString());

	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);
		Intent intent = getIntent();
		i = new Intent(this, Servico.class);
		i.putExtra("servico", "mural");
		i.putExtra("handler", new Messenger(handler));
		i.putExtra("tituloJogo", intent.getStringExtra("tituloJogo"));
		if(intent != null) {
//			if(intent.getBooleanExtra("testeMural", false))
//				carregaMuralTeste();
//			else
				signInWithFacebook();
		}
	}

	public void post(String msg) {
		adapter.add(msg);
	}

	public void post(List<String> msgs) {
		for(String msg : msgs)
			post(msg);
	}

	private void carregaMural() {
		WebServiceInterface wsi = WebServiceInterface.getInstance();
		setContentView(R.layout.chat_wall);
		t = new TextView(this); 
		t = (TextView)findViewById(R.id.tituloView); 
		tituloJogo = getIntent().getStringExtra("tituloJogo");
		t.setText(tituloJogo);
		Log.w("!!!", "ID_ " + tituloJogo);
		try {
			muralId = wsi.getIdMural(tituloJogo);
		} catch (Exception e) {

		}
		if(muralId == null){
			wsi.createWall(tituloJogo);
			muralId = wsi.getIdMural(tituloJogo);
		}
		Log.w("muralID", "ID " + muralId);
		userName = usuario.getUsername(); // + " " + usuario.getLastName();
		userId = wsi.getUserId(userName);
		if(userId == null) {
			wsi.createUser(userName);
			userId = wsi.getUserId(userName);
		}
		historicoChat = new Mural(tituloJogo);
		l = new ListView(this);
		l = (ListView)findViewById(R.id.chatView);
		historicoChat.adicionaMensagem("O chat estara aberto ate o final do dia");
		startService(i);
		adapter=new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				historicoChat.getHistoricoChat());
		l.setAdapter(adapter);
		e = new EditText(this);
		e = (EditText) findViewById(R.id.mensagemEdit);
		e.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				e.setText("");

			}
		});
		chBox = (CheckBox) findViewById(R.id.checkBoxCompartilhar);
		bt = new Button(this);
		bt = (Button) findViewById(R.id.enviarButton);
		bt.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String msg = e.getText().toString();
				System.out.println(msg);
				if(!(msg.trim().equals(""))){
					Calendar c = Calendar.getInstance();
					//					adapter.insert(userName + " "+ c.getTime().toString().substring(11,19) + " - " + msg, 0);
					e.setText("");
					WebServiceInterface.getInstance().postMessage(muralId, userId, msg);
					if(chBox.isChecked()){
						CompartilharMensagemTask compartilharTask = new CompartilharMensagemTask(GamePage.this);
						compartilharTask.execute("O usuário " + usuario.getName() + " comentou no jogo " + tituloJogo + ": " + msg);
					}
				}
			}
		});
	}

	private void carregaMuralTeste() {
		WebServiceInterface wsi = WebServiceInterface.getInstance();
		setContentView(R.layout.chat_wall);
		t = new TextView(this); 
		t = (TextView)findViewById(R.id.tituloView); 
		tituloJogo = getIntent().getStringExtra("tituloJogo");
		t.setText(tituloJogo);
		Log.w("!!!", "ID_ " + tituloJogo);
		try {
			muralId = wsi.getIdMural(tituloJogo);
		} catch (Exception e) {
		
		}
		if(muralId == null){
			wsi.createWall(tituloJogo);
			muralId = wsi.getIdMural(tituloJogo);
		}
		Log.w("muralID", "ID " + muralId);
		userName = "mark";
		//		user = usuario.getFirstName() + " " + usuario.getLastName();
		userId = wsi.getUserId(userName);
		if(userId == null) {
			wsi.createUser(userName);
			userId = wsi.getUserId(userName);
		}
		historicoChat = new Mural(tituloJogo);
		l = new ListView(this);
		l = (ListView)findViewById(R.id.chatView);
		historicoChat.adicionaMensagem("O chat estara aberto ate o final do dia");
		/*		for(String str : wsi.loadMessages(tituloJogo))
			historicoChat.adicionaMensagem(str);*/
		startService(i);
		adapter=new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				historicoChat.getHistoricoChat());
		l.setAdapter(adapter);
		e = new EditText(this);
		e = (EditText) findViewById(R.id.mensagemEdit);
		e.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				e.setText("");

			}
		});
		chBox = (CheckBox) findViewById(R.id.checkBoxCompartilhar);
		bt = new Button(this);
		bt = (Button) findViewById(R.id.enviarButton);
		bt.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				try {
					String msg = e.getText().toString();
					if(!(msg.trim().equals(""))){
						Calendar c = Calendar.getInstance();
						//					adapter.insert(usuario.getFirstName() + " " + usuario.getLastName() /*+ " "+ c.getTime().toString().substring(11,19) + " - "*/ + msg, 0);
						//					adapter.add(String.format("%s: %s", userName, msg));
						e.setText("");
						WebServiceInterface.getInstance().postMessage(muralId, userId, msg);
					}
				} catch(Exception e) {
					Log.w("!!!", ""+e.getMessage());
				}
			}
		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
		stopService(i);
	}

	private void signInWithFacebook() {


		Session.openActiveSession(this, true, new Session.StatusCallback() {

			// callback when session changes state
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isOpened()) {

					// make request to the /me API
					Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

						// callback after Graph API response with user object
						@Override
						public void onCompleted(GraphUser user, Response response) {
							if (user != null) {
								usuario = user;
								carregaMural();
							}
						}
					});
				}
			}
		});


	}


}
